<template>
  <div class="login-bg">
    <div class="login-wrapper">
      <!-- 左侧宣传栏 -->
      <div class="login-left">
        <div class="brand">
          <img src="@/assets/lgo2222.png" alt="logo" class="brand-logo" />
        </div>
        <h2 class="main-title">{{ $t("接受免费付费调查！") }}</h2>
        <h3 class="sub-title">
          {{ $t("兑换免费PaypalCash，") }}<br />
          {{ $t("比特币和礼品卡！") }}
        </h3>
        <p class="desc">
          {{ $t("从200多种奖励中选择，包括") }}<br />
          {{ $t("亚马逊礼品卡、比特币和PayPal现金") }}
        </p>
        <button class="watch-btn">
          <span class="watch-icon">▶</span> {{ $t("观看以开始") }}
        </button>
        <div class="awards">
          <div class="awards-title">{{ $t("特色奖项") }}</div>
          <div class="awards-list">
            <img src="@/assets/award1.png" alt="award" />
            <img src="@/assets/award2.png" alt="award" />
            <img src="@/assets/award3.png" alt="award" />
            <img src="@/assets/award4.png" alt="award" />
            <img src="@/assets/award5.png" alt="award" />
            <img src="@/assets/award6.png" alt="award" />
          </div>
        </div>
      </div>
      <!-- 右侧重置密码卡片 -->
      <div class="login-right">
        <div class="card">
          <div class="card-title">{{ $t("重置密码") }}</div>
          <el-form :model="form" :rules="rules" ref="resetFormRef" class="form" @submit.prevent="onSubmit">
            <el-form-item prop="email">
              <el-input v-model="form.email" :placeholder="$t('您的电子邮件')" size="large" />
            </el-form-item>
            <el-form-item prop="verificationCode">
              <div style="display:flex;gap:10px;align-items:center;">
                <el-input v-model="form.verificationCode" :placeholder="$t('验证码')" size="large" />
                <el-button type="primary" :disabled="countdown > 0" @click="sendVerificationCode" size="large">
                  {{ countdown > 0 ? `${countdown}s` : $t('获取代码') }}
                </el-button>
              </div>
            </el-form-item>
            <el-form-item prop="password">
              <el-input v-model="form.newPassword" type="password" :placeholder="$t('新密码')" size="large" show-password />
            </el-form-item>
            <el-form-item prop="confirmPassword">
              <el-input v-model="form.confirmPassword" type="password" :placeholder="$t('确认密码')" size="large" show-password />
            </el-form-item>
            <el-button type="primary" class="signup-btn" @click="onSubmit" :loading="loading">{{ $t("重置密码") }}</el-button>
          </el-form>
          <div class="login-link">
            {{ $t("记起密码了？") }}
            <a @click="$router.push('/login')" class="link">{{ $t("登录") }}</a>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, reactive, computed } from 'vue'
import { useRouter } from 'vue-router'
import { useStore } from 'vuex'
import { sendMsg, updatePassword } from '../../api/index'
import { ElMessage } from 'element-plus'
import { Message, Key, Lock } from '@element-plus/icons-vue'
import LanguageSwitcher from '../../components/LanguageSwitcher.vue'

export default {
  name: 'ResetPassword',
  components: {
    Message,
    Key,
    Lock,
    LanguageSwitcher
  },
  setup() {
    const router = useRouter()
    const store = useStore()
    const loading = ref(false)
    const countdown = ref(0)
    const form = reactive({
      email: '',
      verificationCode: '',
      newPassword: '',
      confirmPassword: ''
    })

    const validateConfirmPassword = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入新密码'))
      } else if (value !== form.newPassword) {
        callback(new Error('两次输入的密码不一致'))
      } else {
        callback()
      }
    }

    const rules = reactive({
      email: [
        { required: true, message: '请输入邮箱地址', trigger: 'blur' },
        { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
      ],
      verificationCode: [
        { required: true, message: '请输入验证码', trigger: 'blur' }
      ],
      newPassword: [
        { required: true, message: '请输入新密码', trigger: 'blur' },
        { min: 6, max: 20, message: '密码长度在 6 到 20 个字符', trigger: 'blur' }
      ],
      confirmPassword: [
        { required: true, message: '请再次输入新密码', trigger: 'blur' },
        { validator: validateConfirmPassword, trigger: 'blur' }
      ]
    })

    const resetFormRef = ref(null)

    const sendVerificationCode = async () => {
      if (!form.email) {
        ElMessage.warning({
          message: '请先输入邮箱地址',
          offset: 100,
          duration: 5000
        })
        return
      }
      
      if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(form.email)) {
        ElMessage.warning({
          message: '请输入正确的邮箱格式',
          offset: 100,
          duration: 5000
        })
        return
      }

      try {
        // 调用发送验证码API，type=4表示重置密码
        const response = await sendMsg({
          username: form.email,
          type: 4
        })
        
        if (response.code === 10000) {
          ElMessage.success({
            message: '验证码已发送',
            offset: 100,
            duration: 5000
          })
          
          // 开始倒计时
          countdown.value = 120
          const timer = setInterval(() => {
            countdown.value--
            if (countdown.value <= 0) {
              clearInterval(timer)
            }
          }, 1000)
        } else {
          ElMessage.error({
            message: response.message || '验证码发送失败，请重试',
            offset: 100,
            duration: 5000
          })
        }
      } catch (error) {
        console.error('发送验证码失败:', error)
        ElMessage.error({
          message: '验证码发送失败，请重试',
          offset: 100,
          duration: 5000
        })
      }
    }

    const onSubmit = async () => {
      if (!resetFormRef.value) return
      
      try {
        const valid = await resetFormRef.value.validate()
        if (valid) {
          loading.value = true
          try {
            // 调用重置密码API
            const response = await updatePassword({
              username: form.email,
              password: form.newPassword,
              code: form.verificationCode
            })
            
            if (response.code === 10000) {
              ElMessage.success({
                message: 'Password reset successful',
                offset: 100,
                duration: 5000
              })
              // 重置成功后跳转到登录页
              setTimeout(() => {
                resetFormRef.value.resetFields()
                countdown.value = 0
                loading.value = false
                router.push('/login')
              }, 1500)
            } else {
              ElMessage.error({
                message: response.message || 'Password reset failed, please try again',
                offset: 100,
                duration: 5000
              })
              loading.value = false
            }
          } catch (error) {
            console.error('重置密码失败:', error)
            ElMessage.error({
              message: '密码重置失败，请重试',
              offset: 100,
              duration: 5000
            })
            loading.value = false
          }
        }
      } catch (error) {
        ElMessage.error({
          message: '请检查输入信息',
          offset: 100,
          duration: 5000
        })
      }
    }

    return {
      form,
      loading,
      countdown,
      sendVerificationCode,
      onSubmit,
      resetFormRef,
      rules,
      getCurrentText: (chineseText, englishText) => {
          if (!chineseText || !englishText) return chineseText || englishText || ''
          return store.getters.currentLanguage === 'zh' ? chineseText : englishText
        },
        logoUrl: computed(() => {
          const shopData = store.getters.shopData
          const imgUrl = store.state.imgUrl
          
          if (shopData && shopData.logo_img) {
            const fullUrl = imgUrl + shopData.logo_img
            return fullUrl
          }
          
          // 如果没有获取到logo_img，则使用默认图片
          return new URL('@/assets/lgo.png', import.meta.url).href
        })
    }
  }
}
</script>

<style lang="scss" scoped>
.login-bg {
  min-height: 100vh;
  background-image: url('@/assets/bbbbggg.png');
  background-size: 100% 100%;
  background-repeat: no-repeat;
  display: flex;
  align-items: center;
  justify-content: center;
}
.login-wrapper {
  display: flex;
  width: 100%;
  max-width: 1100px;
  min-height: 600px;
  background: transparent;
  border-radius: 16px;
  box-sizing: border-box;
  padding: 32px;
  gap: 40px;
}
.login-left {
  flex: 1.2;
  display: flex;
  flex-direction: column;
  justify-content: center;
  padding-left: 32px;
  color: #222;
  .brand {
    display: flex;
    align-items: center;
    margin-bottom: 32px;
    .brand-logo {
      width: 249px;
      height: 96px;
      margin-right: 16px;
    }
    .brand-title {
      font-size: 32px;
      font-weight: 600;
      letter-spacing: 1px;
    }
  }
  .main-title {
    font-size: 32px;
    font-weight: 800;
    margin-bottom: 16px;
  }
  .sub-title {
    font-size: 28px;
    font-weight: 700;
    margin-bottom: 18px;
    line-height: 1.2;
  }
  .desc {
    font-size: 16px;
    margin-bottom: 24px;
    color: #333;
  }
  .watch-btn {
    background: #4faaff;
    color: #fff;
    border: none;
    border-radius: 24px;
    padding: 12px 32px;
    font-size: 18px;
    font-weight: 600;
    margin-bottom: 32px;
    cursor: pointer;
    box-shadow: 0 4px 16px rgba(79,170,255,0.15);
    .watch-icon {
      font-size: 20px;
      margin-right: 8px;
      vertical-align: middle;
    }
  }
  .awards {
    margin-top: 24px;
    .awards-title {
      font-size: 16px;
      font-weight: 600;
      margin-bottom: 12px;
    }
    .awards-list {
      display: flex;
      gap: 18px;
      img {
        width: 48px;
        height: 32px;
        object-fit: contain;
      }
    }
  }
}
.login-right {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  .card {
    background: rgba(255,255,255,0.95);
    border-radius: 18px;
    box-shadow: 0 8px 32px rgba(79,170,255,0.10);
    padding: 40px 32px;
    min-width: 340px;
    max-width: 370px;
    display: flex;
    flex-direction: column;
    align-items: center;
    .card-title {
      font-size: 24px;
      font-weight: 700;
      margin-bottom: 12px;
      color: #222;
      text-align: center;
    }
    .welcome-bonus {
      background: #ffe6ee;
      color: #ff4d6b;
      font-size: 14px;
      font-weight: 600;
      border-radius: 12px;
      padding: 6px 18px;
      margin-bottom: 24px;
      text-align: center;
    }
    .form {
      width: 100%;
      .el-form-item {
        margin-bottom: 18px;
      }
      .el-input__wrapper {
        background: #f3f8ff;
        border-radius: 12px;
        border: 1px solid #e0e7ff;
      }
      .el-input__inner {
        font-size: 16px;
        color: #222;
      }
    }
    .terms {
      font-size: 13px;
      color: #888;
      margin-bottom: 18px;
      text-align: left;
      .link {
        color: #4faaff;
        text-decoration: underline;
        margin: 0 2px;
      }
    }
    .signup-btn {
      width: 100%;
      height: 48px;
      background: linear-gradient(90deg, #ff4d6b 0%, #ffb86b 100%);
      border: none;
      border-radius: 24px;
      color: #fff;
      font-size: 18px;
      font-weight: 700;
      margin-bottom: 18px;
      cursor: pointer;
    }
    .or {
      color: #888;
      font-size: 15px;
      margin-bottom: 10px;
      text-align: center;
    }
    .login-link {
      font-size: 15px;
      color: #888;
      .link {
        color: #4faaff;
        margin-left: 4px;
        cursor: pointer;
        text-decoration: underline;
      }
    }
  }
}
@media (max-width: 900px) {
  .login-wrapper {
    flex-direction: column;
    gap: 24px;
    padding: 16px;
  }
  .login-left {
    padding-left: 0;
    align-items: center;
    text-align: center;
    .brand {
      justify-content: center;
    }
    .awards-list {
      justify-content: center;
    }
  }
  .login-right {
    .card {
      min-width: 100%;
      max-width: 100%;
      padding: 32px 16px;
    }
  }
}
</style>
